package com.mercury.tools;

import org.apache.commons.codec.digest.DigestUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

public class WxPayData {

    static String wx_appid = "wxcf6fe3913ff1cf68";
    static String wx_appsecret = "6f7154f0a1adc10e655fe2af4d204ee0";
    static String wx_mechid = "1500553471";
    static String wx_mechkey = "YyY12344321YyY12344321YyY1234432";


    private TreeMap<String, Object> m_values = new TreeMap<String, Object>();

    public void setValue(String key, Object value) {
        m_values.put(key, value);
    }

    public Object getValue(String key) {
        return m_values.get(key);
    }

    public void fromXml(Document document) {
        Element root = document.getRootElement();
        for (Element element : root.elements()) {
            m_values.put(element.getName(), element.getText());
        }
    }

    public String toXml() {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("xml");
        for (String key : m_values.keySet()) {
            root.addElement(key).addText(m_values.get(key).toString());
        }
        return document.asXML();
    }

    public String makeSign() {
        StringBuilder sign = new StringBuilder();
        for (String key : m_values.keySet()) {
            sign.append(key).append("=").append(m_values.get(key).toString()).append("&");
        }
        sign.append("key=").append(wx_mechkey);

        System.out.println("签名数据：" + sign);
        System.out.println("签名MD5：" + DigestUtils.md5Hex(sign.toString()).toUpperCase());

        return DigestUtils.md5Hex(sign.toString()).toUpperCase();
    }
}
